package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.Const;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.*;
import com.flea.hclv.model.entity.*;
import com.flea.hclv.model.entity.vo.HOderVO;
import com.flea.hclv.model.entity.vo.HVisitorOderQueryVo;
import com.flea.hclv.model.entity.vo.HVisitorOrderDetailVo;
import com.flea.hclv.model.entity.vo.ProductTimeTableVo;
import com.flea.hclv.service.HCarVisitorService;
import com.flea.hclv.service.HVisitorOrderRelationService;
import com.flea.hclv.service.HVisitorOrderService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.base.util.StringUtil;
import com.flea.system.bean.FleaPage;
import com.flea.system.entity.OrgDept;
import com.flea.system.entity.OrgUser;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: project
 * @description: 地接社游客订单
 * @author: shiliqiang
 * @create: 2018-10-13 17:52
 * @version: 1.0
 */
@Service
public class HVisitorOrderServiceImpl implements HVisitorOrderService {

    private static final Logger logger = LoggerFactory
            .getLogger(HVisitorOrderServiceImpl.class);

    @Autowired
    private HVisitorOrderRelationMapper hVisitorOrderRelationMapper;
    @Autowired
    private HVisitorOrderMapper hVisitorOrderMapper;
    @Autowired
    private HTimeTableMapper hTimeTableMapper;
    @Autowired
    private HProductMapper hProductMapper;
    @Autowired
    private HResourceRelationMapper hResourceRelationMapper;
    @Autowired
    private HVisitorOrderDebtMapper hVisitorOrderDebtMapper;
    @Autowired
    private HTravelGroupMapper hTravelGroupMapper;
    @Autowired
    private HVisitorRebackPaymentRecoderMapper hVisitorRebackPaymentRecoderMapper;
    @Autowired
    private HTourGroupVisitorMapper tourGroupVisitorMapper;
    @Autowired
    private HVisitorMapper hVisitorMapper;
    @Autowired
    private HVisitorOrderRelationService visitorOrderRelationService;
    @Autowired
    private HCarVisitorService hCarVisitorService;

    // @Override
    // public ServerResponse<Map<String,String>> pay(String orderNo, String
    // userId, String path) {
    //
    // Map<String,String> map= Maps.newHashMap();
    // HVisitorOrder order=hVisitorOrderMapper.selectByOrderNo(orderNo);
    // if (order == null) {
    // return ServerResponse.createByErrorMessage("用户没有该订单");
    // }
    // map.put("orderNo",order.getOrderNo());
    //
    //
    // // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
    // // 需保证商户系统端不能重复，建议通过数据库sequence生成，
    // String outTradeNo = order.getOrderNo();
    //
    // // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
    // String subject = new
    // StringBuilder().append("mmall扫码支付，订单号：").append(outTradeNo).toString();
    //
    // // (必填) 订单总金额，单位为元，不能超过1亿元
    // // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
    // String totalAmount = order.getPayment().toString();
    //
    // // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
    // // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
    // String undiscountableAmount = "0";
    //
    // // 卖家支付宝账号ID，用于支持一个签约账号下持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
    // // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
    // String sellerId = "";
    //
    // // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
    // String body = new
    // StringBuilder().append("订单").append(outTradeNo).append("共购买商品").append(totalAmount).append("元").toString();
    //
    // // 商户操作员编号，添加此参数可以为商户操作员做销售统计
    // String operatorId = userId;
    //
    // // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
    // String storeId = order.getStoreId();
    //
    // // 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，详情请咨询支付宝技术支持
    // ExtendParams extendParams = new ExtendParams();
    // extendParams.setSysServiceProviderId("2088100200300400500");
    //
    // // 支付超时，定义为120分钟
    // String timeoutExpress = "120m";
    //
    // // 商品明细列表，需填写购买商品详细信息，
    // List<GoodsDetail> goodsDetailList = Lists.newArrayList();
    // HTimeTable hTimeTable =
    // hTimeTableMapper.selectByPrimaryKey(order.getProductTimeTableId());
    // HProduct hProduct =
    // hProductMapper.selectByPrimaryKey(hTimeTable.getProductId());
    // GoodsDetail goodsDetail = new GoodsDetail();
    // goodsDetail.setPrice(order.getPayment().longValue());
    // goodsDetail.setQuantity(order.getQuantity());
    // goodsDetail.setAlipayGoodsId(hTimeTable.getId());
    // goodsDetail.setGoodsId(hTimeTable.getId());
    // goodsDetail.setGoodsName(hProduct.getName());
    // goodsDetailList.add(goodsDetail);
    //
    //
    //
    //
    // // 创建扫码支付请求builder，设置请求参数
    // AlipayTradePrecreateRequestBuilder builder = new
    // AlipayTradePrecreateRequestBuilder()
    // .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
    // .setUndiscountableAmount(undiscountableAmount).setSellerId(sellerId).setBody(body)
    // .setOperatorId(operatorId).setStoreId(storeId).setExtendParams(extendParams)
    // .setTimeoutExpress(timeoutExpress)
    // //
    // .setNotifyUrl("http://www.test-notify-url.com")//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
    // .setGoodsDetailList(goodsDetailList);
    //
    //
    // /** 一定要在创建AlipayTradeService之前调用Configs.init()设置默认参数
    // *
    // Configs会读取classpath下的zfbinfo.properties文件配置信息，如果找不到该文件则确认该文件是否在classpath目录
    // */
    // Configs.init("zfbinfo.properties");
    //
    // /** 使用Configs提供的默认参数
    // * AlipayTradeService可以使用单例或者为静态成员对象，不需要反复new
    // */
    // AlipayTradeService tradeService = new
    // AlipayTradeServiceImpl.ClientBuilder().build();
    //
    // AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
    // switch (result.getTradeStatus()) {
    // case SUCCESS:
    // logger.info("支付宝预下单成功: )");
    //
    // AlipayTradePrecreateResponse response = result.getResponse();
    // dumpResponse(response);
    //
    // File folder=new File(path);
    // if (!folder.exists()){
    // folder.setWritable(true);
    // folder.mkdir();
    // }
    //
    // // 需要修改为运行机器上的路径 二维码路径
    // String qrPath = String.format(path+"/qr-%s.png",
    // response.getOutTradeNo());
    // String qrFileName = String.format("qr-%s.png", response.getOutTradeNo());
    // ZxingUtils.getQRCodeImge(response.getQrCode(), 256, qrPath);
    //
    // File targetFile=new File(path,qrFileName);
    // // try {
    // //// FTPUtil.uploadFile(Lists.newArrayList(targetFile));
    // //// } catch (IOException e) {
    // //// logger.error("上传二维码失败",e);
    // //// }
    // logger.info("qrPath:" + qrPath);
    // // String qrUrl= PropertiesUtil.getProperty("前缀"+targetFile);
    // map.put("qrUrl","");
    // return ServerResponse.createBySuccess(map);
    //
    // case FAILED:
    // logger.error("支付宝预下单失败!!!");
    // return ServerResponse.createByErrorMessage("支付宝预下单失败!!!");
    //
    // case UNKNOWN:
    // logger.error("系统异常，预下单状态未知!!!");
    // return ServerResponse.createByErrorMessage("系统异常，预下单状态未知!!!");
    //
    // default:
    // logger.error("不支持的交易状态，交易返回异常!!!");
    // return ServerResponse.createByErrorMessage("不支持的交易状态，交易返回异常!!!");
    // }
    // }
    // // 简单打印应答
    // private void dumpResponse(AlipayResponse response) {
    // if (response != null) {
    // logger.info(String.format("code:%s, msg:%s", response.getCode(),
    // response.getMsg()));
    // if (StringUtils.isNotEmpty(response.getSubCode())) {
    // logger.info(String.format("subCode:%s, subMsg:%s", response.getSubCode(),
    // response.getSubMsg()));
    // }
    // logger.info("body:" + response.getBody());
    // }
    // }

    @Override
    public ServerResponse<List<HVisitorOrder>> selectOrderList(String userId) {
        List<HVisitorOrder> hVisitorOrders = hVisitorOrderMapper
                .selectByCreateUser(userId);
        return ServerResponse.createBySuccess(hVisitorOrders);
    }



    @Override
    public ServerResponse<String> pay(HVisitorOrder order, String userId) {
        if (order == null) {
            return ServerResponse.createByErrorMessage("订单参数错误");
        }
        HVisitorOrder hVisitorOrder = hVisitorOrderMapper.selectByOrderNo(order
                .getOrderNo());
        if (hVisitorOrder == null) {
            return ServerResponse.createByErrorMessage("没有找到该订单");
        }
        // 判断是否分期
        /*
         * if (Const.OrderStatusEnum.BY_STAGES.getCode() ==
         * order.getPaymentType()) { HVisitorOrderDebt hVisitorOrderDebt = new
         * HVisitorOrderDebt();
         * hVisitorOrderDebt.setId(FleaStringUtils.getGenerateUUID());
         * hVisitorOrderDebt.setCreateUser(userId);
         * hVisitorOrderDebt.setModifyUser(userId);
         * hVisitorOrderDebt.setReturnMoney(order.getPayment());
         * hVisitorOrderDebt.setDebtMoney(order.getTotalAmount() -
         * order.getPayment());
         * hVisitorOrderDebt.setOrderNo(order.getOrderNo()); // todo 还款人 //
         * hVisitorOrderDebt.setReturnPerson();
         * hVisitorOrderDebtMapper.insertSelective(hVisitorOrderDebt);
         * order.setStatus(Const.OrderStatusEnum.BY_STAGES.getCode()); }
         * order.setModifyUser(userId);
         * order.setStatus(Const.OrderStatusEnum.ORDER_SUCCESS.getCode());
         * hVisitorOrderMapper.updateByPrimaryKey(order);
         */
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse<Map<String, String>> createOrder(String userId,
                                                           OrgDept currentUserDept, ProductTimeTableVo productVo,
                                                           List<String> visitorIds, String paymentPersonId) {
        if (productVo == null || visitorIds.size() == 0) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        // 检验库存
        int quantity = productVo.getQuantity();
        HTimeTable hTimeTable = hTimeTableMapper.selectByPrimaryKey(productVo
                .getTimeTableId());
        if (hTimeTable.getRestPersonNum() < quantity) {
            return ServerResponse.createByErrorMessage("库存不足");
        }
        // 找到产品供应商
        HProduct hProduct = hProductMapper.selectByPrimaryKey(productVo
                .getProductId());
        // 生成订单
        HVisitorOrder order = this.assembleOrder(hProduct, userId,
                currentUserDept, productVo, paymentPersonId);
        hVisitorOrderMapper.insertSelective(order);
        // 更新库存
        hTimeTable.setRestPersonNum(hTimeTable.getRestPersonNum() - quantity);
        hTimeTableMapper.updateByPrimaryKeySelective(hTimeTable);
        ;

        // 添加游客订单关联
        List<HVisitorOrderRelation> relations = this.addVisitorOrderRelation(
                visitorIds, order.getOrderNo(), userId);
        hVisitorOrderRelationMapper.insertBatch(relations);
        Map<String, String> map = new HashMap<>();
        map.put("orderNo", order.getOrderNo());
        return ServerResponse.createBySuccess(map);
    }

    private HVisitorOrder assembleOrder(HProduct hProduct, String userId,
                                        OrgDept currentUserDept, ProductTimeTableVo productVo,
                                        String paymentPersonId) {
        HVisitorOrder order = new HVisitorOrder();
        order.setId(FleaStringUtils.getGenerateUUID());
        // 设置供应商
        order.setSupplierId(hProduct.getUuid());
        // 设置门店
        order.setStoreId(currentUserDept != null ? currentUserDept
                .getDeptUuid() : HConstant.HCLV_ADMIN_ADMIN);
        String orderNo = FleaStringUtils.getGenerateUUID();
        order.setOrderNo(orderNo);
        order.setCreateUser(userId);
        order.setModifyUser(userId);
        order.setPayment(productVo.getPrice() * productVo.getQuantity());
        order.setPaymentPerson(paymentPersonId);
        /* order.setStatus(Const.OrderStatusEnum.NO_PAY.getCode()); */
        return order;
    }

    private List<HVisitorOrderRelation> addVisitorOrderRelation(
            List<String> visitorIds, String orderNo, String userId) {
        List<HVisitorOrderRelation> relations = new ArrayList<>();
        for (String visitorId : visitorIds) {
            HVisitorOrderRelation relation = new HVisitorOrderRelation();
            relation.setId(FleaStringUtils.getGenerateUUID());
            relation.setVisitorId(visitorId);
            relation.setOrderNo(orderNo);
            relation.setCreateUser(userId);
            relation.setModifyUser(userId);
            relations.add(relation);
        }
        return relations;
    }

    @Override
    public ServerResponse<ProductTimeTableVo> placeAnOrder(String timeTableId) {
        // 根据产品班期ID查询
        if (timeTableId == null) {
            return ServerResponse.createByErrorMessage("班期ID为空");
        }
        return this.assembleProductVo(timeTableId);
    }

    private ServerResponse<ProductTimeTableVo> assembleProductVo(
            String timeTableId) {
        HTimeTable hTimeTable = hTimeTableMapper
                .selectByPrimaryKey(timeTableId);
        HProduct hProduct = hProductMapper.selectByPrimaryKey(hTimeTable
                .getProductId());
        if (hProduct == null) {
            return ServerResponse.createByErrorMessage("没有找到产品或班期");
        }
        List<HResourceRelation> hResourceRelation = hResourceRelationMapper
                .selectByUuid(hProduct.getId());

        // 判断产品状态
        if (hTimeTable.getValid().equals(Const.ProductStatus.UN_SALE)) {
            return ServerResponse.createByErrorMessage("该产品班期不在售卖状态");
        }
        // 判断产品库存
        if (hTimeTable.getRestPersonNum() == 0) {
            return ServerResponse.createByErrorMessage("该产品已售空");
        }
        ProductTimeTableVo productVo = new ProductTimeTableVo();
        productVo.setProductId(hProduct.getId());
        productVo.setMainImage(hResourceRelation.size() == 0 ? null
                : hResourceRelation.get(0).getPath());
        productVo.setProductName(hProduct.getName());
        productVo.setTitle(hProduct.getTitle());
        productVo.setPrice(hTimeTable.getSalePriceAdult());
        productVo.setTimeTableId(timeTableId);
        return ServerResponse.createBySuccess(productVo);
    }

    /*************************************** 新 *********************************************************************************/
    @Override
    public ServerResponse<HVisitorOrder> addOrder(HttpServletRequest request, String model)throws Exception {

        HVisitorOrder visitorOder = new HVisitorOrder();
        // 1、查询
        HOderVO oderVo = JSONObject.parseObject(model, HOderVO.class);
        logger.info("游客订单,HOderVO：{}",oderVo);
        List<HVisitor> vistors = oderVo.getAddVisitors();
        String userId = FleaOrgUtils.getCurUserUuid(request);
        OrgDept curOrgDept = FleaOrgUtils.getCurrentUserDept(request);
        if (null == curOrgDept) {
            logger.error("未获取部门信息");
            return ServerResponse.createByErrorMessage("未获取部门信息");
        }
        String serviceOrgId = curOrgDept.getDeptUuid();
        String serviceDeptName = curOrgDept.getDeptName();
        String timeTableId = oderVo.getTimeTableId();
        String groupName = null;
        HTimeTable obj = hTimeTableMapper.selectForUpdateByPrimId(timeTableId);
        if(null==obj){
          return ServerResponse.createByErrorMessage("该产品无此班期");
        }
        Date timeDate = obj.getDate();
        Date currentDate = new Date();
        if(!currentDate.before(timeDate)){
          return ServerResponse.createByErrorMessage("该产品班期已经超过今天的订票日期，不可进行购买，请购买其他班期");
        }

        HProduct hProduct = null;
        //对外销售价格
        Float auditPrice = obj.getSalePriceAdult();
        Float childPrice = obj.getSalePriceChild();
        Float otherPrice = obj.getSalePriceOther();
        //结算价格
        Float autidCostPrice = obj.getCostPrice();
        Float childCostPrice = obj.getCostPriceChild();
        Float otherCostPrice = obj.getCostPriceOther();


        // 查询获取产品是否在销售状态
        hProduct = hProductMapper.selectByPrimaryKey(obj.getProductId());
        String status = hProduct.getStatus();
        if (status.equals(HConstant.HCLV_PRODUCT_SALE_STATUS_LOAD)) {
            logger.info("产品已下架");
            return ServerResponse.createByErrorMessage("产品已下架,暂不可售");
        }
      SimpleDateFormat sf = new SimpleDateFormat("yyyy_MM_dd");
      //产品名称+班期时间+组团社名称
      groupName = hProduct.getName() + "_" + sf.format(obj.getDate()) + serviceDeptName;
        Integer auditNum = 0;
        Integer childNum = 0;
        Integer otherNum = 0;

        for (HVisitor hVisitor : vistors) {
            if (HConstant.D_VISITOR_TYPE_ADULT.equals(hVisitor.getType())) {
                auditNum += 1;
                continue;
            }
            if (HConstant.D_VISITOR_TYPE_CHILDREN.equals(hVisitor.getType())) {
                childNum += 1;
                continue;
            }
            if (HConstant.D_VISITOR_TYPE_OTHER.equals(hVisitor.getType())) {
                otherNum += 1;
            } else {
                auditNum += 1;
            }

        }
        logger.info("游客订单成人数量：{}",auditNum);
        logger.info("游客订单儿童数量：{}",childNum);
        logger.info("游客订单其他数量：{}",otherNum);
        oderVo.setAuditNum(auditNum);
        oderVo.setChidNum(childNum);
        oderVo.setOtherNum(otherNum);
        Integer totalNum = oderVo.getAuditNum() + oderVo.getChidNum()+ oderVo.getOtherNum();
        float totalCost = auditNum*autidCostPrice+childNum*childCostPrice+otherNum*otherCostPrice;
        float realSale = auditNum*auditPrice+childNum*childPrice+otherNum*otherPrice;
        Float payment = 0f;

      // 该班期剩余人数足够，还可以下单
        if (obj.getRestPersonNum() >= totalNum) {
            // 创建订单,计算订单价格，判断是否需要创建团

            visitorOder.setCreateUser(userId);
            String id = FleaStringUtils.getGenerateUUID();
            visitorOder.setId(id);
            visitorOder.setModifyUser(userId);
            String orderNo = FleaStringUtils.getOrderIdByTime();
            visitorOder.setOrderNo(orderNo);
            visitorOder.setProductTimeTableId(timeTableId);
            visitorOder.setQuantity(totalNum);
            // 实际应该支付的钱
             payment = oderVo.getAuditNum() * auditPrice + oderVo.getChidNum() * childPrice + oderVo.getOtherNum() * otherPrice;
            // visitorOder.setPayment(payment);
            visitorOder.setTotalAmount(payment);
            // 未支付
            visitorOder.setStatus(HConstant.D_ORDER_STATUS_INITIALIZATION);
            visitorOder.setStoreId(serviceOrgId);
            if (null != hProduct) {
                visitorOder.setSupplierId(hProduct.getUuid());
            }
            // 订单创建成功，判断是这个产品的团已经存在
            HTravelGroup group = hTravelGroupMapper.selectByTimeTableIdAndOrgIdForUpdate(timeTableId, serviceOrgId);
            if (null != group) {
                /**
                 * 判断团的状态，如果是
                 */
                String groupStatus = group.getStatus();
                if (!HConstant.HCLV_VISITOR_GROUP_ISNO.equals(groupStatus)) {
                    return ServerResponse.createByErrorMessage("本期产品已经封团，请选择其他班期的产品");
                }
            }
          String groupId;
            if(null==group){
              groupId = FleaStringUtils.getGenerateUUID();
            }else{
              groupId = group.getId();
            }

          visitorOder.setGroupId(groupId);
          float groupRealCost = payment;
            logger.info("添加游客订单：订单号：{},订单金额：{}，订单人数，{},供应商id：{},门店id:{}",
                visitorOder.getOrderNo(),visitorOder.getPayment(),visitorOder.getQuantity(),visitorOder.getSupplierId(),visitorOder.getStoreId());
            boolean result = hVisitorOrderMapper.insertSelective(visitorOder) == 1;
            List<HVisitorOrderRelation> vistorOrderRelations = new ArrayList<>();

            if (result) {
                Integer curPerson = obj.getRestPersonNum() - totalNum;
                obj.setRestPersonNum(curPerson);
                obj.setModifyUser(userId);
                boolean resultUpdate = hTimeTableMapper.updateByPrimaryKeySelective(obj) == 1;
                if (!resultUpdate) {
                    logger.error("更新人数失败");
                    return ServerResponse.createByErrorMessage("更新人数失败");
                }
                // 团已经存在，更新团数据
                if (null != group) {
                    Integer curPersonNum = group.getPersonNum();
                    curPersonNum += totalNum;
                    group.setPersonNum(curPersonNum);
                    //总成本
                    Float oldCost = group.getTotelCost();
                    if(null==oldCost){
                      oldCost=0f;
                    }
                    //总成本
                    Float oldRealSale = group.getRealSale();
                    if(null==oldRealSale){
                      oldRealSale=0f;
                    }
                    logger.info("团Id:{},团总成本：{}",groupId,totalCost);
                    group.setTotelCost(totalCost+oldCost);
                    group.setRealSale(realSale+oldRealSale);
                    group.setModifyUser(userId);
                    int updatePnum = 0;
                    try {
                        updatePnum = hTravelGroupMapper.updateByPrimaryKeySelective(group);
                    } catch (Exception e) {
                        logger.error("更新团信息失败",e);
                        throw new Exception("更新团信息失败");
                    }
                    if (updatePnum != 1) {
                        logger.error("更新团信息失败");
                        return ServerResponse.createByErrorMessage("更新团信息失败");
                    }

                } else {
                    // 团不存在， 创建新的团

                     group = new HTravelGroup();
                  group.setCreateUser(userId);
                  group.setModifyUser(userId);
                  group.setPersonNum(totalNum);
                  group.setStatus(HConstant.HCLV_VISITOR_GROUP_ISNO);
                  group.setTimeTableId(timeTableId);
                  group.setId(groupId);
                  group.setServiceOrgId(serviceOrgId);
                  group.setSupplierId(hProduct.getUuid());
                  String groupNo = FleaStringUtils.getOrderIdByTime();

                    //总成本
//                    float totalCost = totalNum * hProduct.getCostPrice();
                  group.setTotelCost(totalCost);
                  group.setRealSale(realSale);
                    logger.info("团Id:{},团总成本：{}",groupId,totalCost);
                    logger.info("团Id:{},团总销售：{}",groupId,totalCost);
                  group.setGroupNo(groupNo);
                  group.setGroupName(groupName);
                    int saveResult = hTravelGroupMapper.insertSelective(group);
                    if (saveResult != 1) {
                        logger.error("创建团失败");
                        return ServerResponse.createByErrorMessage("创建团失败");
                    }
                }
                for (HVisitor hVisitor : vistors) {
                    HVisitorOrderRelation vhr = new HVisitorOrderRelation();
                    vhr.setCreateUser(userId);
                    vhr.setModifyUser(userId);
                    vhr.setOrderNo(orderNo);
                    vhr.setId(FleaStringUtils.getGenerateUUID());
                    vhr.setVisitorId(hVisitor.getId());
                    vistorOrderRelations.add(vhr);
                }
                hVisitorOrderRelationMapper.insertBatch(vistorOrderRelations);
                this.addGroupVisitorRelation(vistors, userId, groupId);

            } else {
                logger.info("订单创建失败");
                return ServerResponse.createByErrorMessage("订单创建失败");
                // 订单创建失败，返回状态码
            }

        } else {
            // 人数不够，不足下单
            logger.info("余量不足，创建订单失败");
            return ServerResponse.createByErrorMessage("余量不足，创建订单失败");
        }
        logger.info("订单创建成功,订单：{}",visitorOder);
         ServerResponse s = hCarVisitorService.saveSeatNumber(userId,model);
         if(!s.isSuccess()){
           return s;
         }
        return ServerResponse.createBySuccess("订单创建成功", visitorOder);
    }

    @Override
    public ServerResponse<HVisitorOrder> updateOrder(
            HttpServletRequest request, String model) throws Exception {
        // 订单状态（挂单，支付完成，待支付，分期），修改人数，修改总价，（不可修改产品价格，不可修改班期价格）；
        // 修改数量：团的人数，产品人数，班期人数,更新订单与人员关联信息表

        // 1、查询
        HOderVO orderVo = JSONObject.parseObject(model, HOderVO.class);
        // 修改不能在订单中添加人数
        // List<HVisitor> addVistor = orderVo.getAddVistors();
        List<HVisitor> delVistor = orderVo.getDelVistors();
        Integer delNums = null != delVistor ? delVistor.size() : 0;
        String userId = FleaOrgUtils.getCurUserUuid(request);
        String serviceOrgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        // String serviceOrgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        String orderNo = orderVo.getOrderNo();
        String comment = orderVo.getComment();
        HVisitorOrder oldOrder = hVisitorOrderMapper.selectByOrderNo(orderNo);

        String timeTableId = oldOrder.getProductTimeTableId();
        HTravelGroup oldGroup = hTravelGroupMapper.findByServiceOrgIdAndTimeTableId(serviceOrgId,timeTableId);
        String groupId = oldGroup.getId();

        HTimeTable oldTimeTable = hTimeTableMapper.selectByPrimaryKey(timeTableId);
        oldOrder.setModifyUser(userId);
        oldOrder.setComment(comment);
        Float shouldRebakPayment = 0f;

        // 需要判断团的状态，需要判断团的状体，如果未出团，出团，回团，只有未出团的时候可以取消订单，出团的只允许修改价格，不允许删除订单，可在团里修改
        // TODO
        String oldGroupStatus = oldGroup.getStatus();
        if (oldGroupStatus.equals(HConstant.HCLV_VISITOR_GROUP_ISNO)) {
            // 游客类修改订单的几种方式：1、取消订单，修改订单，完成订单,已退款
            // 游客所有应用的几种状态：1、未支付（未出游）2、已支付（未出游）3、已支付（已出游）4、游客已游玩结束 5 订单已完成

            // 取消订单
            if (oldOrder.getStatus().equals(HConstant.D_ORDER_STATUS_INITIALIZATION)) {
                // 直接取消订单，修改订单与游客关系表，修改团信息，修改班期表中的数据
                // TODO 订单添加备注字段
                oldOrder.setStatus(HConstant.D_ORDER_STATUS_CANCEL);
                shouldRebakPayment = oldOrder.getPayment();
                oldOrder.setTotalAmount(oldOrder.getTotalAmount() - shouldRebakPayment);
                boolean cancalResult = hVisitorOrderMapper
                        .updateForCancelOder(oldOrder) == 1;
                logger.info("取消订单，订单：{},结果：{}",oldOrder,cancalResult);
                if (cancalResult) {
                    // 应当锁表

                    Integer groupPnums = oldGroup.getPersonNum();
                    groupPnums -= delNums;

                    oldGroup.setModifyUser(userId);
                    oldGroup.setPersonNum(groupPnums);

                    boolean updateGroupResult = hTravelGroupMapper
                            .updateByPrimaryKey(oldGroup) == 1;
                    if (!updateGroupResult) {
                        logger.error("更新团信息失败,团：{}",oldGroup);
                        return ServerResponse.createByErrorMessage("更新团信息失败");
                    }
                }
                // 将游客从团中移除

                hVisitorOrderRelationMapper.deleteBatch(delVistor);
                this.deleteBatchVisitorGroupRelation(delVistor, userId, groupId);

            }
            if (oldOrder.getStatus().equals(HConstant.D_ORDER_STATUS_PARTPAY)
                    || oldOrder.getStatus().equals(
                    HConstant.D_ORDER_STATUS_PAYDONE)) {
                // TODO
                // 进行退款流程，系统要记录，并且要记录，判断
                this.addRebackRecoder(request, orderNo, shouldRebakPayment);

                oldOrder.setStatus(HConstant.D_ORDER_STATUS_CLOSE);
                shouldRebakPayment = oldOrder.getPayment();
                oldOrder.setTotalAmount(oldOrder.getTotalAmount()
                        - shouldRebakPayment);
                boolean cancalResult = hVisitorOrderMapper
                        .updateForCancelOder(oldOrder) == 1;
                logger.info("退款流程,退款金额：{},订单号：{}",shouldRebakPayment,orderNo);
                logger.info("取消订单，订单：{},结果：{}",oldOrder,cancalResult);
                if (cancalResult) {
                    // 应当锁表

                    Integer groupPnums = oldGroup.getPersonNum();
                    groupPnums -= delNums;

                    oldGroup.setModifyUser(userId);
                    oldGroup.setPersonNum(groupPnums);

                    boolean updateGroupResult = hTravelGroupMapper
                            .updateByPrimaryKey(oldGroup) == 1;
                    if (!updateGroupResult) {
                        logger.info("更新团信息失败,团：{}",oldGroup);
                        return ServerResponse.createByErrorMessage("更新团信息失败");
                    }
                }
                // 将游客从团中移除

                hVisitorOrderRelationMapper.deleteBatch(delVistor);
                this.deleteBatchVisitorGroupRelation(delVistor, userId, groupId);
                Integer tpnum = oldTimeTable.getRestPersonNum();
                tpnum += delNums;
                oldTimeTable.setRestPersonNum(tpnum);
                // 更新班期中的剩余人数
                hTimeTableMapper.updateByPrimaryKeySelective(oldTimeTable);
            }
        }
        if (oldGroupStatus.equals(HConstant.HCLV_VISITOR_GROUP_ISREBACK)) {
            // 更新订单总价
            Float updateMoney = orderVo.getTotalAmount();

            // 不允许取消订单只允许修改价格，不更新团人数信息
            shouldRebakPayment = oldOrder.getPayment() - updateMoney;
            oldOrder.setModifyUser(userId);
            oldOrder.setComment(comment);
            hVisitorOrderMapper.updateByPrimaryKeySelective(oldOrder);
            logger.info("更新订单价格，订单：{}",oldOrder);
            this.addRebackRecoder(request, orderNo, shouldRebakPayment);

        }
        if (oldGroupStatus.equals(HConstant.HCLV_VISITOR_GROUP_ISCLOSE)) {
            logger.info("不允许修改订单，该团已经关闭");
            return ServerResponse.createByErrorMessage("不允许修改订单，该团已经关闭");
        }
        logger.info("订单更新成功,订单：{}",oldOrder);
        return ServerResponse.createBySuccessMessage("订单更新成功");
    }
  /**
   * TODO取消订单，要更新团的人员信息，车位信息，更新团的价格信息,如果未出团，那么可以更新其他信息
   * @param orderNo
   * @param userId
   * @return
   * @throws Exception
   */
  @Override
  public ServerResponse<String> cancel(String orderNo, String userId) throws  Exception {
    HVisitorOrder order = hVisitorOrderMapper.selectByOrderNo(orderNo);
    if (order == null) {
      return ServerResponse.createByErrorMessage("订单不存在");
    }
    if(HConstant.D_ORDER_STATUS_SUCCESS_OK.equals(order.getStatus())){
      return ServerResponse.createByErrorMessage("订单交易已经完成，不可取消订单");
    }
    String groupId = order.getGroupId();
    HTravelGroup group = hTravelGroupMapper.selectByPrimaryKey(groupId);
    if(null==group){
      return ServerResponse.createByErrorMessage("不存在该团的订单，请检查团是否存在");
    }
    if(HConstant.HCLV_VISITOR_GROUP_ISYES.equals(group.getStatus())){
      return ServerResponse.createByErrorMessage("该订单所在的团，正在出团中，不能取消订单，请先解封");
    }
    if(!HConstant.HCLV_VISITOR_GROUP_ISNO.equals(group.getStatus())){
      return ServerResponse.createByErrorMessage("该订单所在的团，不在未出团状态，不能取消订单");
    }
    // order.setStatus(Const.OrderStatusEnum.CANCELED.getCode());
    // 更新库存
    HTimeTable hTimeTable = hTimeTableMapper.selectByPrimaryKey(order.getProductTimeTableId());
    HTimeTable hTimeTable1 = new HTimeTable();
    hTimeTable1.setId(hTimeTable.getId());
    hTimeTable1.setRestPersonNum(hTimeTable.getRestPersonNum()+ order.getQuantity());
    hTimeTable1.setModifyUser(userId);
    boolean result = 1==hTimeTableMapper.updateByPrimaryKeySelective(hTimeTable1);
    if(!result){
      throw new Exception("订单取消失败,更新班期表信息失败");
    }
    order.setStatus(HConstant.D_ORDER_STATUS_CANCEL);
    order.setModifyUser(userId);
    result = hVisitorOrderMapper.updateByPrimaryKeySelective(order)==1;
    if(!result){
      throw new Exception("订单取消失败，更新订单状态失败");
    }
    List<HVisitorOrderRelation> relations = hVisitorOrderRelationMapper.findByOrderNo(orderNo);
    List<HVisitor> delVisitor = new ArrayList<>();
    for (HVisitorOrderRelation vs: relations) {
      HVisitor temp =  new HVisitor();
      temp.setId(vs.getVisitorId());
      delVisitor.add(temp);
    }
    hVisitorOrderRelationMapper.deleteBatch(delVisitor);
    this.deleteBatchVisitorGroupRelation(delVisitor, userId, groupId);


    ServerResponse s =  hCarVisitorService.cancelSeatNumber(hTimeTable.getId(),delVisitor);
    if(!s.isSuccess()){
      throw new Exception("订单取消，取消排座失败");
    }
    return ServerResponse.createBySuccess("取消成功");
  }

    /**
     * 退款记录表
     *
     * @description TODO
     * @methodName addRebackRecoder
     * @returnType void
     * @throw
     */
    private boolean addRebackRecoder(HttpServletRequest request, String oderNo,
                                     Float shouldRebakPayment) {

        HVisitorRebackPaymentRecoder rebackRecoder = new HVisitorRebackPaymentRecoder();
        String rebackReoderId = FleaStringUtils.getGenerateUUID();

        rebackRecoder.setId(rebackReoderId);
        rebackRecoder.setCode(FleaStringUtils.getGenerateUUID());
        rebackRecoder.setRebackPayment(shouldRebakPayment);
        rebackRecoder.setOrderNo(oderNo);
        String creatorId = FleaOrgUtils.getCurUserUuid(request);
        rebackRecoder.setCreateUser(creatorId);
        boolean result = hVisitorRebackPaymentRecoderMapper
                .insertSelective(rebackRecoder) == 1;

        return result;

    }

    /**
     * 批量添加游客与图团之间的关联关系
     *
     * @description TODO
     * @methodName addGroupVisitorRelation
     * @returnType void
     * @throw
     */
    public void addGroupVisitorRelation(List<HVisitor> vistors, String userId,
                                        String tourGroupId) throws Exception {

        // List<HTourGroupVisitor> groupVisitorRelations = new
        // ArrayList<HTourGroupVisitor>();
        for (HVisitor hVisitor : vistors) {
            HTourGroupVisitor vgr = new HTourGroupVisitor();
            vgr.setCreateUser(userId);
            vgr.setTourGroupId(tourGroupId);
            vgr.setModifyUser(userId);
            vgr.setVisitorId(hVisitor.getId());
            vgr.setId(FleaStringUtils.getGenerateUUID());

            tourGroupVisitorMapper.insertSelective(vgr);
        }
    }

    /**
     * @description 批量移除关系，软删除，需要删除么，待考虑
     * @methodName deleteBatchVisitorGroupRelation
     * @returnType void
     * @throw
     */
    public void deleteBatchVisitorGroupRelation(List<HVisitor> vistors,
                                                String userId, String groupId) throws Exception {

        for (HVisitor hVisitor : vistors) {
            HTourGroupVisitor vgr = new HTourGroupVisitor();
            vgr.setCreateUser(userId);
            vgr.setModifyUser(userId);
            vgr.setVisitorId(hVisitor.getId());
            vgr.setValid("N");

            tourGroupVisitorMapper.deleteByVistorAndGroupSelective(vgr);
        }
    }

    @Override
    public ServerResponse<FleaPage<HVisitorOrder>> findVisitorOderByOrgId(
            HttpServletRequest request, String model, int indexPage,
            int pageSize) {
        RowBounds rowBounds = new RowBounds(indexPage, pageSize);
        String orgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        // String userId = FleaOrgUtils.getCurUserUuid(request);
        HVisitorOderQueryVo qvo = JSONObject.parseObject(model,
                HVisitorOderQueryVo.class);
        if (null == qvo) {
            qvo = new HVisitorOderQueryVo();
        }
        if (null != qvo.getUserName()) {
            List<OrgUser> users = FleaOrgUtils.getUserByExactName(qvo
                    .getUserName());
            if (null != users) {
                List<String> userIds = new ArrayList<String>();
                userIds = getUserIds(users);
                qvo.setUserIds(userIds);
            }
        }

        qvo.setOrgId(orgId);
        List<HVisitorOrder> oders = hVisitorOrderMapper.findByVisorQueryOvPaging(rowBounds, qvo);
        FleaPage<HVisitorOrder> result = new FleaPage<HVisitorOrder>(oders);
        List<HVisitorOrder> coverAfter = coverCodeToName(oders);

        result.setCurPageData(coverAfter);

        return ServerResponse.createBySuccess(result);
    }

    private List<String> getUserIds(List<OrgUser> users) {
        List<String> userIds = new ArrayList<String>();
        for (OrgUser orgUser : users) {
            userIds.add(orgUser.getUserUuid());
        }
        return userIds;

    }

    private List<HVisitorOrder> coverCodeToName(List<HVisitorOrder> orders) {
        List<HVisitorOrder> result = new ArrayList<HVisitorOrder>();
        for (HVisitorOrder order : orders) {
//      HVisitorOrder order = new HVisitorOrder();
            order.setStoreName(FleaOrgUtils.getOrgDeptByDeptUuid(
                    order.getStoreId()).getDeptName());
            order.setSupplierName(FleaOrgUtils.getOrgDeptByDeptUuid(
                    order.getSupplierId()).getDeptName());
            HTimeTable t = hTimeTableMapper.selectByPrimaryKey(order.getProductTimeTableId());
            HProduct p = hProductMapper.selectByPrimaryKey(null == t ? null : t.getProductId());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(p == null ? "" : p.getName());
            stringBuilder.append("_");
            stringBuilder.append(t == null ? "" : dateFormat.format(t.getDate()));
            order.setTimeDate(String.valueOf(stringBuilder));
            order.setProductName(null == p ? null : p.getName());
            order.setCreateUserName(FleaOrgUtils.getUserNameByUserUuid(order.getCreateUser()));
//      order.setStatus(order.getStatus());
//      order.setPaymentPerson(order.getPaymentPerson());
//      order.setPayment(order.getPayment());
//      order.setQuantity(order.getQuantity());
//      order.setTotalAmount(order.getTotalAmount());
//      order.setEndTime(order.getEndTime());
//      order.setComment(order.getComment());
//      order.setCreateTime(order.getCreateTime());
//      order.setOrderNo(order.getOrderNo());
            result.add(order);

        }

        return result;

    }

    @Override
    public ServerResponse<List<HVisitor>> findVisitorsByOrderId(
            HttpServletRequest request, String orderId) {
        List<HVisitorOrderRelation> result = hVisitorOrderRelationMapper
                .findByOrderNo(orderId);
        List<String> visitorIds = new ArrayList<String>();
        for (HVisitorOrderRelation hVisitorOrderRelation : result) {
            visitorIds.add(hVisitorOrderRelation.getVisitorId());
        }
        List<HVisitor> visitors = hVisitorMapper.findByIds(visitorIds);

        return ServerResponse.createBySuccess(visitors);
    }

    /**
     * 不是待支付状态的不可以进行关闭
     *
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @Override
    public ServerResponse<List<HVisitorOrder>> updateVisitorStatusToClose(
            HttpServletRequest request, String model) throws Exception {
        String userId = FleaOrgUtils.getCurUserUuid(request);
        List<HVisitorOrder> faliOrders = new ArrayList<HVisitorOrder>();
        List<HVisitorOrder> operList = new ArrayList<HVisitorOrder>();
        List<String> orders = JSONObject.parseArray(model,
                String.class);
        for (String s : orders) {
            HVisitorOrder oldOrders = hVisitorOrderMapper
                    .selectByOrderNo(s);
            if (!oldOrders.getStatus().equals(HConstant.D_ORDER_STATUS_INITIALIZATION) && !oldOrders.getStatus().equals(HConstant.D_ORDER_STATUS_CANCEL)) {
                faliOrders.add(oldOrders);
            } else {
                oldOrders.setCloseTime(new Date());
                oldOrders.setModifyUser(userId);
                oldOrders.setStatus(HConstant.D_ORDER_STATUS_CLOSE);
                operList.add(oldOrders);
                boolean result = hVisitorOrderMapper.updateByPrimaryKeySelective(oldOrders) == 1;
                if (!result) {
                    logger.error("订单更新失败,订单:{}",oldOrders);
                    throw new Exception("订单更新失败！");
                }
            }
        }
        if (faliOrders.size() != 0) {
            logger.info("只有取消订单状态和待支付状态才可以进行关闭订单,不能关闭订单：{}",faliOrders);
            return ServerResponse.createBySuccess("这些订单不能够进行关闭,只有取消订单状态和待支付状态才可以进行关闭订单，请联系业务人员", faliOrders);
        } else {
            logger.info("操作成功订单：{}",operList);
            return ServerResponse.createBySuccess("操作成功", operList);
        }
    }

    /**
     * 付完款完成才可以设置ok状态
     *
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @Override
    public ServerResponse<List<HVisitorOrder>> updateVisitorStatusToOk(
            HttpServletRequest request, String model) throws Exception {
        String userId = FleaOrgUtils.getCurUserUuid(request);
        List<HVisitorOrder> faliOrders = new ArrayList<HVisitorOrder>();
        List<HVisitorOrder> operList = new ArrayList<HVisitorOrder>();
        List<String> orders = JSONObject.parseArray(model, String.class);
        for (String s : orders) {
            HVisitorOrder oldOrders = hVisitorOrderMapper.selectByOrderNo(s);
            if (!oldOrders.getStatus().equals(HConstant.D_ORDER_STATUS_PAYDONE)) {
                faliOrders.add(oldOrders);
            } else {
                oldOrders.setCloseTime(new Date());
                oldOrders.setStatus(HConstant.D_ORDER_STATUS_SUCCESS_OK);
                oldOrders.setModifyUser(userId);
                operList.add(oldOrders);
                boolean result = hVisitorOrderMapper.updateByPrimaryKeySelective(oldOrders) == 1;
                if (!result) {
                    logger.error("订单状态更新失败,订单：{}",oldOrders);
                    throw new Exception("订单状态更新失败！");
                }
            }
        }
        if (faliOrders.size() != 0) {
            logger.error("操作成功，但部分关闭失败,这些订单不能够进行关闭,失败订单:{}",faliOrders);
            return ServerResponse.createBySuccess("操作成功，但部分关闭失败,这些订单不能够进行关闭，请联系业务人员", faliOrders);
        } else {
            logger.info("更新成功订单:{}",operList);
            return ServerResponse.createBySuccess("操作成功", operList);
        }
    }

    /**
     * 取消订单不支持批量
     */
    @Override
    public ServerResponse<String> updateVisitorStatusToCancel(HttpServletRequest request,
                                                              String orderNo) throws Exception {
        {
            // 1、查询
            String userId = FleaOrgUtils.getCurUserUuid(request);
            HVisitorOrder oldOrder = hVisitorOrderMapper.selectByOrderNo(orderNo);
            if (oldOrder == null) {
                logger.error("订单取消失败，未找到与订单相关的信息,订单：{}",oldOrder);
                return ServerResponse.createByErrorMessage("订单取消失败，未找到与订单相关的信息");
            }
            String timeTableId = oldOrder.getProductTimeTableId();
            String serverOrgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
//      HTravelGroup oldGroup = hTravelGroupMapper.selectByTimeTableId(timeTableId);
            HTravelGroup oldGroup = hTravelGroupMapper.findByServiceOrgIdAndTimeTableId(serverOrgId, timeTableId);
            if (oldGroup == null) {
                logger.error("订单取消失败，未找到与订单相关的团信息,班期Id：{},服务组织ID:{}",timeTableId,serverOrgId);
                return ServerResponse.createByErrorMessage("订单取消失败，未找到与订单相关的团信息");
            }

            String groupId = oldGroup.getId();
            HTimeTable oldTimeTable = hTimeTableMapper.selectByPrimaryKey(timeTableId);
            if (oldTimeTable == null) {
                logger.error("订单取消失败，改产品的班期已经不存在,班期ID:{}",timeTableId);
                return ServerResponse.createByErrorMessage("订单取消失败，改产品的班期已经不存在");
            }
            Float shouldRebakPayment = 0f;

            List<HVisitorOrderRelation> hVisitorOrderRelations = hVisitorOrderRelationMapper
                    .findByOrderNo(orderNo);
            if (hVisitorOrderRelations == null || hVisitorOrderRelations.size() == 0) {
                logger.error("订单取消失败，未找到与订单相关的游客关联信息,订单号：{}",orderNo);
                return ServerResponse.createByErrorMessage("订单取消失败，未找到与订单相关的游客关联信息");
            }

            // 需要判断团的状态，需要判断团的状体，如果未出团，出团，回团，只有未出团的时候可以取消订单
            String oldGroupStauts = oldGroup.getStatus();
            //只有支付的才需要进行退款
            if (oldGroupStauts.equals(HConstant.HCLV_VISITOR_GROUP_ISNO)) {
                // 游客类修改订单的几种方式：1、取消订单
                // 游客所有应用的几种状态：1、未支付（未出游）2、已支付（未出游）3、已支付（已出游）4、游客已游玩结束 5 订单已完成
                if (!oldOrder.getStatus().equals(HConstant.D_ORDER_STATUS_INITIALIZATION)) {
                    shouldRebakPayment = oldOrder.getPayment();
                    oldOrder.setTotalAmount(oldOrder.getTotalAmount() - shouldRebakPayment);
                    this.addRebackRecoder(request, orderNo, shouldRebakPayment);
                    // 取消订单   待支付
                }

                // 直接取消订单，修改订单与游客关系表，修改团信息，修改班期表中的数据
                oldOrder.setStatus(HConstant.D_ORDER_STATUS_CANCEL);
                boolean cancalResult = hVisitorOrderMapper.updateForCancelOder(oldOrder) == 1;
                logger.info("取消订单，订单：{},结果：{}",oldOrder,cancalResult);
                if (cancalResult) {
                    // 应当锁表
                    Integer groupPnums = oldGroup.getPersonNum();
                    if (null != groupPnums) {
                        groupPnums -= hVisitorOrderRelations.size();
                        oldGroup.setPersonNum(groupPnums);
                    }

                    oldGroup.setModifyUser(userId);
                    boolean updateGroupResult = hTravelGroupMapper.updateByPrimaryKey(oldGroup) == 1;
                    if (!updateGroupResult) {
                        logger.error("更新团信息失败,团：{}",oldGroup);
                        return ServerResponse.createByErrorMessage("更新团信息失败");
                    }
                }
                // 将游客从团中移除
                int results = hVisitorOrderRelationMapper.deleteBatchByRelation(hVisitorOrderRelations);
                if (results == 0) {
                    logger.error("将游客从团中移除失败，订单取消失败,订单游客关联：{}",hVisitorOrderRelations);
                    throw new Exception("将游客从团中移除失败，订单取消失败");
                }
                List<String> visitorIds = new ArrayList<>();
                for (HVisitorOrderRelation visitorRel :
                        hVisitorOrderRelations) {
                    visitorIds.add(visitorRel.getVisitorId());
                }
                List<HVisitor> delVistor = hVisitorMapper.findByIds(visitorIds);
                this.deleteBatchVisitorGroupRelation(delVistor, userId, groupId);
                Integer tpnum = oldTimeTable.getRestPersonNum();
                tpnum += hVisitorOrderRelations.size();
                oldTimeTable.setRestPersonNum(tpnum);
                // 更新班期中的剩余人数
                boolean timeResult = hTimeTableMapper.updateByPrimaryKeySelective(oldTimeTable) == 1;
                if (!timeResult) {
                    logger.error("班期人数更新失败，订单取消失败,班期：{}",oldTimeTable);
                    throw new Exception("班期人数更新失败，订单取消失败");
                }

            } else {
                logger.info("订单不允许取消");
                return ServerResponse.createByErrorMessage("订单不允许取消");
            }
            logger.info("订单取消成功,订单：{}",oldOrder);
            return ServerResponse.createBySuccessMessage("订单取消成功");
        }
    }

    @Override
    public ServerResponse findOrderDetailById(String orderId) throws Exception {
      List<HVisitor> visitors = new ArrayList<>();
      Map<String,Object> result = new HashMap<>();
      HVisitorOrderDetailVo vo = new HVisitorOrderDetailVo();
        if (StringUtil.isEmpty(orderId)) {
            logger.error("参数非法,订单Id:{}",orderId);
            return ServerResponse.createByErrorMessage("参数非法");
        } else {
            HVisitorOrder order = hVisitorOrderMapper.selectByPrimaryKey(orderId);
            if (null != order) {
                List<HVisitorOrder> lists = new ArrayList<>();
                lists.add(order);

                ServerResponse rs =  visitorOrderRelationService.getVisitorsByOrderNo(order.getOrderNo());
                if(rs.isSuccess()){
                  visitors = (List<HVisitor>)rs.getData();
                  result.put("visitors",visitors);
                  vo.setVisitors(visitors);
                }
                order = this.coverCodeToName(lists).get(0);
                result.put("order",order);
                vo.setOrder(order);
            }
            logger.info("订单详情：{}",order);
            return ServerResponse.createBySuccess("成功", vo);
//            return ServerResponse.createBySuccess("成功", order);
        }

    }

  @Override
  public ServerResponse findByGroupId(String model, HttpServletRequest request, int index,
      int pageSize) throws Exception {
      //根据团id,获取所有的游客订单信息
    if(StringUtil.isEmpty(model)){
      return  ServerResponse.createByErrorMessage("未获取到参数团ID");
    }
    RowBounds bounds = new RowBounds(index,pageSize);
    List<HVisitorOrder> data = hVisitorOrderMapper.findByGroupIdForPaging(bounds,model);
    FleaPage<HVisitorOrder> page = new FleaPage<>(data);
    List<HVisitorOrder> newdata = coverCodeToName(data);
    page.setCurPageData(newdata);
    return ServerResponse.createBySuccess(page);
  }

  @Override
  public List<HVisitorOrder> findByGroupIdToList(String id) {
    List<HVisitorOrder> data = hVisitorOrderMapper.findByGroupId(id);
    return data;
  }

  @Override
  public List<HVisitorOrder> findByProductTimeTableIdToList(String timeTableId) {
    List<HVisitorOrder> visitorOrders = hVisitorOrderMapper.selectByTimeTableId(timeTableId);
    return visitorOrders;
  }

  @Override
  public ServerResponse updateVisitorByOrderId(String model, HttpServletRequest request)
      throws Exception {
      String currentUserId = FleaOrgUtils.getCurUserUuid(request);
    if(StringUtil.isEmpty(model)){
      return  ServerResponse.createByErrorMessage("未获取到参数");
    }
    JSONObject jsb = JSONObject.parseObject(model);
    if(null==jsb){
      return  ServerResponse.createByErrorMessage("参数json格式化转版失败");
    }
    String orderNo = jsb.getString("orderNo");
    String oldVisitorId = jsb.getString("oldVisitorId");
    String newVisitorId = jsb.getString("newVisitorId");
    //判断是否已经封团了，封团不可进行人员修改操作
    //判断是否已经向供应商下单了，下单不可进行操作
    //  1、获取oldVisitor所归属的团

    if (StringUtil.isEmpty(orderNo)){
      return  ServerResponse.createByErrorMessage("游客订单号为空，参数非法");
    }
    HVisitorOrder hVisitorOrder =  hVisitorOrderMapper.selectByOrderNo(orderNo);
    if(null==hVisitorOrder){
      return  ServerResponse.createByErrorMessage("游客订单不存在，请检查检查或联系运维人员");
    }
    String groupId = hVisitorOrder.getGroupId();

    HTravelGroup hTravelGroup = hTravelGroupMapper.selectByPrimaryKey(groupId);
    if(null==hTravelGroup){
      return  ServerResponse.createByErrorMessage("旅游团不存在，请检查检查或联系运维人员");
    }
    if(!HConstant.HCLV_VISITOR_GROUP_ISNO.equals(hTravelGroup.getStatus())){
      return  ServerResponse.createByErrorMessage("旅游团不在未出团状态，不能进行修改");
    }

    if(StringUtil.isEmpty(oldVisitorId)){
      return  ServerResponse.createByErrorMessage("传递的游客信息为空");
    }
    if(StringUtil.isEmpty(newVisitorId)){
      return  ServerResponse.createByErrorMessage("传递的游客信息为空");
    }

   HVisitorOrderRelation hvs =  hVisitorOrderRelationMapper.findByOrderNoAndVisitorId(orderNo,oldVisitorId);

    if(null!=hvs){
      hvs.setVisitorId(newVisitorId);
     boolean updateResult =  hVisitorOrderRelationMapper.updateByPrimaryKey(hvs)==1;
     String productTimeTableId = hVisitorOrder.getProductTimeTableId();
     HVisitorOrder hvisitorOrderInfo =  hVisitorOrderMapper.selectByOrderNo(orderNo);
     HVisitor oldVisitor =  hVisitorMapper.selectByPrimaryKey(oldVisitorId);
     HVisitor newVisitor = hVisitorMapper.selectByPrimaryKey(newVisitorId);
     HTimeTable timeTableInfo  = hTimeTableMapper.selectByPrimaryKey(productTimeTableId);
     float oldCostPrice = 0f;
     float oldSalePrice = 0f;
     float newCostPrice = 0f;
     float newSalePrice = 0f;
    //  TODO 补充 根据团的成本价格，销售价格更新，更新团的两个价格；更新团的人数
     if(null!=oldVisitor&&null!=newVisitor){
       //判断两个人分别属于什么类型 成人，老人，其他
      if(oldVisitor.getType().equals(newVisitor.getType())){
        //身份类型完全相同，则可以考虑不用更改订单信息和团信息等
      }else{
        if (HConstant.D_VISITOR_TYPE_ADULT.equals(oldVisitor.getType())) {
          oldCostPrice = timeTableInfo.getCostPrice();
          oldSalePrice = timeTableInfo.getSalePriceAdult();
        }
        if (HConstant.D_VISITOR_TYPE_CHILDREN.equals(oldVisitor.getType())) {
          oldCostPrice = timeTableInfo.getCostPriceChild();
          oldSalePrice = timeTableInfo.getCostPriceChild();
        }
        if (HConstant.D_VISITOR_TYPE_OTHER.equals(oldVisitor.getType())) {

          oldCostPrice = timeTableInfo.getCostPriceOther();
          oldSalePrice = timeTableInfo.getSalePriceOther();

        } else {
         oldCostPrice = timeTableInfo.getCostPrice();
          oldSalePrice = timeTableInfo.getSalePriceOther();
        }
        //new

        if (HConstant.D_VISITOR_TYPE_ADULT.equals(newVisitor.getType())) {
          newCostPrice = timeTableInfo.getCostPrice();
          newSalePrice = timeTableInfo.getSalePriceAdult();
        }
        if (HConstant.D_VISITOR_TYPE_CHILDREN.equals(newVisitor.getType())) {
          newCostPrice = timeTableInfo.getCostPriceChild();
          newSalePrice = timeTableInfo.getCostPriceChild();
        }
        if (HConstant.D_VISITOR_TYPE_OTHER.equals(newVisitor.getType())) {

         newCostPrice = timeTableInfo.getCostPriceOther();
         newSalePrice = timeTableInfo.getSalePriceOther();

        } else {
         newCostPrice  = timeTableInfo.getCostPrice();
         newSalePrice  = timeTableInfo.getSalePriceOther();
        }
        float restCost = oldCostPrice - newCostPrice;
        float restSale = oldSalePrice - newSalePrice;


        // 游客订单价格发生变化
       float currentSale =  hvisitorOrderInfo.getTotalAmount()-restSale;
       hvisitorOrderInfo.setTotalAmount(currentSale);
       hvisitorOrderInfo.setModifyUser(currentUserId);
        updateResult = hVisitorOrderMapper.updateByPrimaryKeySelective(hVisitorOrder)==1;
        if(!updateResult){
          throw new  Exception("订单价格发生变化，但是更新失败！");
        }
        // 旅游团的价格发生变化
        float groupCurrentSale = hTravelGroup.getRealSale()-restSale;
        float groupCurrentCost = hTravelGroup.getTotelCost()-restCost;

        hTravelGroup.setTotelCost(groupCurrentCost);
        hTravelGroup.setRealSale(groupCurrentSale);
        hTravelGroup.setModifyUser(currentUserId);
        updateResult = hTravelGroupMapper.updateByPrimaryKeySelective(hTravelGroup)==1;
        if(!updateResult){
          throw new  Exception("团价格发生变化，但是更新失败！");
        }

      }
     }
     if(!updateResult){
       throw new  Exception("订单信息更新失败");
     }
     return ServerResponse.createBySuccessMessage("订单信息更新成功，请注意是否需要进行退款和追加款项 ");
    }else{
      return ServerResponse.createByErrorMessage("关联信息不存在，订单更新失败！");
    }

  }

  @Override
  public ServerResponse delVisitorByOrderNoAndVisitorId(String model, HttpServletRequest request)
      throws Exception {
    String currentUserId = FleaOrgUtils.getCurUserUuid(request);
    if(StringUtil.isEmpty(model)){
      return  ServerResponse.createByErrorMessage("未获取到参数");
    }
    JSONObject jsb = JSONObject.parseObject(model);
    if(null==jsb){
      return  ServerResponse.createByErrorMessage("参数json格式化转版失败");
    }
    String orderNo = jsb.getString("orderNo");
    String visitorId = jsb.getString("visitorId");
    //判断是否已经封团了，封团不可进行人员修改操作
    //判断是否已经向供应商下单了，下单不可进行操作
    //  1、获取oldVisitor所归属的团

    if (StringUtil.isEmpty(orderNo)){
      return  ServerResponse.createByErrorMessage("游客订单号为空，参数非法");
    }
    HVisitorOrder hVisitorOrder =  hVisitorOrderMapper.selectByOrderNo(orderNo);
    if(null==hVisitorOrder){
      return  ServerResponse.createByErrorMessage("游客订单不存在，请检查检查或联系运维人员");
    }
    String groupId = hVisitorOrder.getGroupId();

    HTravelGroup hTravelGroup = hTravelGroupMapper.selectByPrimaryKey(groupId);
    if(null==hTravelGroup){
      return  ServerResponse.createByErrorMessage("旅游团不存在，请检查检查或联系运维人员");
    }
    if(!HConstant.HCLV_VISITOR_GROUP_ISNO.equals(hTravelGroup.getStatus())){
      return  ServerResponse.createByErrorMessage("旅游团不在未出团状态，不能进行修改");
    }
    if(StringUtil.isEmpty(visitorId)){
      return  ServerResponse.createByErrorMessage("传递的游客信息为空");
    }
    String productTimeTableId = hVisitorOrder.getProductTimeTableId();
    HVisitor visitor = hVisitorMapper.selectByPrimaryKey(visitorId);
    HTimeTable timeTableInfo  = hTimeTableMapper.selectByPrimaryKey(productTimeTableId);
    float oldCostPrice = 0f;
    float oldSalePrice = 0f;
    float newCostPrice = 0f;
    float newSalePrice = 0f;
    HVisitorOrderRelation hvs =  hVisitorOrderRelationMapper.findByOrderNoAndVisitorId(orderNo,visitorId);
    if(null!=hvs){
      boolean updateResult = hVisitorOrderRelationMapper.deleteByPrimaryKey(hvs.getId())==1;
      HVisitorOrder hvisitorOrderInfo =  hVisitorOrderMapper.selectByOrderNo(orderNo);
      if (HConstant.D_VISITOR_TYPE_ADULT.equals(visitor.getType())) {
        oldCostPrice = timeTableInfo.getCostPrice();
        oldSalePrice = timeTableInfo.getSalePriceAdult();
      }
      if (HConstant.D_VISITOR_TYPE_CHILDREN.equals(visitor.getType())) {
        oldCostPrice = timeTableInfo.getCostPriceChild();
        oldSalePrice = timeTableInfo.getCostPriceChild();
      }
      if (HConstant.D_VISITOR_TYPE_OTHER.equals(visitor.getType())) {

        oldCostPrice = timeTableInfo.getCostPriceOther();
        oldSalePrice = timeTableInfo.getSalePriceOther();

      } else {
        oldCostPrice = timeTableInfo.getCostPrice();
        oldSalePrice = timeTableInfo.getSalePriceOther();
      }


      // 游客订单价格发生变化
      float currentSale =  hvisitorOrderInfo.getTotalAmount()-oldSalePrice;
      hvisitorOrderInfo.setTotalAmount(currentSale);
      hvisitorOrderInfo.setModifyUser(currentUserId);
      updateResult = hVisitorOrderMapper.updateByPrimaryKeySelective(hVisitorOrder)==1;
      if(!updateResult){
        throw new  Exception("订单价格发生变化，但是更新失败！");
      }
      // 旅游团的价格发生变化
      float groupCurrentSale = hTravelGroup.getRealSale()-oldSalePrice;
      float groupCurrentCost = hTravelGroup.getTotelCost()-oldCostPrice;

      hTravelGroup.setTotelCost(groupCurrentCost);
      hTravelGroup.setRealSale(groupCurrentSale);
      hTravelGroup.setModifyUser(currentUserId);
      updateResult = hTravelGroupMapper.updateByPrimaryKeySelective(hTravelGroup)==1;
      if(!updateResult){
        throw new  Exception("团价格发生变化，但是更新失败！");
      }
      return ServerResponse.createBySuccessMessage("订单信息更新成功 ");
      //、、TODO 产品班期中的余量需要增加一个人；将汽车座位号需要还回去
    }else{
      return ServerResponse.createByErrorMessage("关联信息不存在，订单更新失败！");
    }
  }

  @Override
  public ServerResponse<FleaPage<HVisitorOrder>> getAllNoCompleteVisitorListByUserId(
      HttpServletRequest request, String model, int indexPage, int pageSize)  {
    RowBounds rowBounds = new RowBounds(indexPage, pageSize);
    String orgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
    String userId  = FleaOrgUtils.getCurUserUuid(request);
    // String userId = FleaOrgUtils.getCurUserUuid(request);
    HVisitorOderQueryVo qvo = JSONObject.parseObject(model,
        HVisitorOderQueryVo.class);
    if (null == qvo) {
      qvo = new HVisitorOderQueryVo();
    }
    qvo.setOrderStatus(HConstant.D_ORDER_STATUS_SUCCESS_OK);
/*    if (null != qvo.getUserName()) {
      List<OrgUser> users = FleaOrgUtils.getUserByExactName(qvo
          .getUserName());
      if (null != users) {
        List<String> userIds = new ArrayList<String>();
        userIds = getUserIds(users);
        qvo.setUserIds(userIds);
      }
    }*/

    qvo.setOrgId(orgId);
    qvo.setCreateUserId(userId);
    List<HVisitorOrder> oders = hVisitorOrderMapper.findByVisorQueryOvPagingByCreateUserIdNoComplete(rowBounds, qvo);
    FleaPage<HVisitorOrder> result = new FleaPage<HVisitorOrder>(oders);
    List<HVisitorOrder> coverAfter = coverCodeToName(oders);

    result.setCurPageData(coverAfter);

    return ServerResponse.createBySuccess(result);
  }

  @Override
  public ServerResponse<FleaPage<HVisitorOrder>> getAlllistCompleteVisiterOrder(
      HttpServletRequest request, String model, int indexPage, int pageSize) {
    {
      RowBounds rowBounds = new RowBounds(indexPage, pageSize);
      String orgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
      // String userId = FleaOrgUtils.getCurUserUuid(request);
      HVisitorOderQueryVo qvo = JSONObject.parseObject(model,
          HVisitorOderQueryVo.class);
      if (null == qvo) {
        qvo = new HVisitorOderQueryVo();
      }
      if (null != qvo.getUserName()) {
        List<OrgUser> users = FleaOrgUtils.getUserByExactName(qvo
            .getUserName());
        if (null != users) {
          List<String> userIds = new ArrayList<String>();
          userIds = getUserIds(users);
          qvo.setUserIds(userIds);
        }
      }

      qvo.setOrgId(orgId);
      List<HVisitorOrder> oders = hVisitorOrderMapper.findByVisorQueryOvPaging(rowBounds, qvo);
      FleaPage<HVisitorOrder> result = new FleaPage<HVisitorOrder>(oders);
      List<HVisitorOrder> coverAfter = coverCodeToName(oders);
      qvo.setOrderStatus(HConstant.D_ORDER_STATUS_SUCCESS_OK);
      result.setCurPageData(coverAfter);

      return ServerResponse.createBySuccess(result);
    }
  }


}
